package com.yuba.front.controller.user;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.io.FileUtil;
import com.yuba.common.core.domain.R;
import com.yuba.common.core.domain.event.OssUploadEvent;
import com.yuba.common.core.domain.model.EmailBindBody;
import com.yuba.common.core.utils.file.MimeTypeUtils;
import com.yuba.common.core.validate.EditGroup;
import com.yuba.common.idempotent.annotation.RepeatSubmit;
import com.yuba.common.log.annotation.Log;
import com.yuba.common.log.enums.BusinessType;
import com.yuba.common.satoken.utils.LoginHelper;
import com.yuba.front.domain.bo.FrontUserBo;
import com.yuba.front.domain.vo.FrontUserVo;
import com.yuba.front.service.IFrontUserService;
import com.yuba.front.service.impl.FrontOssService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;

/**
 * 前台用户接口
 *
 * @author modakai
 * @date 2024-11-30
 */
@RestController
@RequestMapping("api/user")
@RequiredArgsConstructor
public class ApiFrontUserController {

    private final IFrontUserService userService;

    private final FrontOssService ossService;

    /**
     * 检查用户名是否存在
     */
    @SaIgnore
    @PostMapping("exist/{username}")
    public R<Boolean> checkUser(@PathVariable String username) {
        FrontUserBo frontUserBo = new FrontUserBo();
        frontUserBo.setUsername(username);
        return R.ok(userService.isExist(frontUserBo));
    }


    /**
     * 获取当前用户信息
     * @param bo 条件
     * @return 用户信息
     */
    @SaIgnore
    @PostMapping("profile")
    public R<FrontUserVo> profile(@RequestBody FrontUserBo bo) {
        return R.ok(userService.queryById(bo.getUserId()));
    }

    /**
     * 修改密码
     *
     */
    @SaIgnore
    @PostMapping("update/password")
    public R<Boolean> updatePassword(@RequestBody FrontUserBo bo) {
        return R.ok(userService.updatePassword(bo));
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("info")
    public R<FrontUserVo> info() {
        FrontUserVo frontUserVo = userService.queryById(LoginHelper.getUserId());
        return R.ok(frontUserVo);
    }

    /**
     * 绑定邮箱
     * @return 无
     */
    @PostMapping("/bind/email")
    public R<Void> bindEmail(@RequestBody @Validated EmailBindBody form) {
        userService.bindEmail(form.getEmail(), form.getEmailCode());
        return R.ok();
    }


    /**
     * 修改用户信息
     */
    @PostMapping("modify/info")
    public R<Void> modifyInfo(@Validated(EditGroup.class) @RequestBody FrontUserBo form) {
        form.setUserId(LoginHelper.getUserId()); // 防止篡改
        form.setUsername(null);
        form.setStatus(null); // 防止篡改
        form.setPassword(null);// 防止篡改
        userService.updateByBo(form);
        return R.ok();
    }

    public record AvatarVo(String imgUrl) {}
    /**
     * 头像上传
     *
     * @param avatarfile 用户头像
     */
    @RepeatSubmit
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<AvatarVo> avatar(@RequestPart("avatarfile") MultipartFile avatarfile) {
        if (!avatarfile.isEmpty()) {
            String extension = FileUtil.extName(avatarfile.getOriginalFilename());
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return R.fail("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            OssUploadEvent oss = ossService.upload(avatarfile);
            String avatar = oss.getUrl();
            if (userService.updateUserAvatar(LoginHelper.getUserId(), oss.getOssId())) {
                AvatarVo avatarVo = new AvatarVo(avatar);
                return R.ok(avatarVo);
            }
        }
        return R.fail("上传图片异常");
    }
}
